package dao

import (
	"goBasic/zhangxiaokun/bean"
	"math/rand"
	"sort"
)

type TransaDao struct {
	TrMapHashId map[int]*bean.Transa		// key:hashId, 		value:Transa,	用于按hashId查找
	TrMapUserId map[int]*bean.Transa		// key:FromUserId	value:Transa,	用于按UserId查找
	maxId int
}

func (transaDao *TransaDao) init()  {
	if transaDao.TrMapHashId == nil {
		transaDao.TrMapHashId = make(map[int]*bean.Transa)
		transaDao.TrMapUserId = make(map[int]*bean.Transa)
		transaDao.maxId = rand.Int()*1000
	}
}


/*
增
 */
func (transaDao *TransaDao) SaveTransa(transa *bean.Transa) (HashId int) {
	if transaDao.TrMapHashId == nil {
		transaDao.init()
	}
	transa.HashId = transaDao.makeId()
	transaDao.TrMapHashId[transa.HashId] = transa
	transaDao.TrMapUserId[transa.FromUserId] = transa

	return transa.HashId
}

/*
删
 */
func(transaDao *TransaDao) DeleteTransa (hashId int)  {
	delete(transaDao.TrMapHashId, hashId)
}

/*
改
 */
func (transaDao *TransaDao) UpdateTransa(transa *bean.Transa)  {
	if transaDao.TrMapHashId[transa.HashId] != nil {

		transaDao.TrMapHashId[transa.HashId] = transa
	}
}


/*
查
 */
func (transaDao *TransaDao) GetTransa(hashId int) *bean.Transa {
	return transaDao.TrMapHashId[hashId]
}

/**
自增生成主键id
 */
func (transaDao *TransaDao) makeId() (hashId int){
	transaDao.maxId +=1
	return transaDao.maxId
}

/**
获取所有交易记录
 */
func (transaDao *TransaDao) GetAllTransa () []*bean.Transa {
	hashIdList := make([]int,0)
	transaList := make([]*bean.Transa, 0)

	map1 := transaDao.TrMapHashId

	//取主键
	for k,_ := range transaDao.TrMapHashId {
		hashIdList = append(hashIdList, k)
	}
	//排序
	sort.Ints(hashIdList)

	//取交易记录
	for _, hashId := range hashIdList {
		transaList = append(transaList, map1[hashId])
	}

	return transaList
}


